<template>
  <main class="form-signin">
    <div class="alert alert-danger" role="alert" v-show="wrong">
      Invalid input or duplicated username!
    </div>
    <form>
      <br>
      <br>
      <img class="mb-4" src="../assets/register.svg" alt="" width="72" height="57">
      <h1 class="h3 mb-3 fw-normal">Register for Book Store</h1>

      <div class="form-floating">
        <input type="tel" class="form-control" id="floatingInput" placeholder=" " v-model="tel">
        <label for="floatingInput">Telephone</label>
      </div>
      <div class="form-floating">
        <input type="tel" class="form-control" id="floatingName" placeholder=" " v-model="name">
        <label for="floatingName">Name</label>
      </div>
      <div class="form-floating">
        <input type="tel" class="form-control" id="floatingAddress" placeholder=" " v-model="address">
        <label for="floatingAddress">Address</label>
      </div>
      <div class="form-floating">
        <input type="password" class="form-control" id="floatingPassword" placeholder=" " v-model="pwd">
        <label for="floatingPassword">Password</label>
      </div>
      <br>
      <br>
      <button type="button" class="w-100 btn btn-lg btn-primary" @click="reg">Submit</button>
    </form>
  </main>
</template>

<script>
import axios from "axios";
import {ref} from 'vue';
import {useRouter} from "vue-router";
import {useStore} from "vuex";

export default {
  name: "register",
  setup(){
    const store = useStore();
    const router = useRouter();
    store.dispatch("Load");

    let name = ref("");
    let tel = ref("");
    let address = ref("");
    let pwd = ref("");
    let wrong = ref(false);

    const reg = ()=>{
      store.dispatch("Load")
      if(name.value === "" || tel.value === "" || address.value === "" || pwd.value === ""){
        store.dispatch("Finished");
        wrong.value = true;
      }else{
        axios({
          async:false,
          url:"RegisterServlet",
          params:{
            name:name.value,
            tel:tel.value,
            address:address.value,
            pwd:pwd.value
          }
        }).then((res)=>{
          store.dispatch("Finished");
          if(res.data === true){
            router.replace("/login")
          }else{
            wrong.value = true;
          }
        })
      }
    }

    store.dispatch("Finished");
    return{
      name,
      tel,
      address,
      pwd,
      reg,
      wrong
    }
  }
}
</script>

<style scoped>

.form-signin {
  width: 100%;
  max-width: 330px;
  padding: 15px;
  margin: auto;
}

.form-signin .checkbox {
  font-weight: 400;
}

.form-signin .form-floating:focus-within {
  z-index: 2;
}

.form-signin input[type="tel"] {
  margin-bottom: -1px;
  border-bottom-right-radius: 0;
  border-bottom-left-radius: 0;
}

.form-signin input[type="password"] {
  margin-bottom: 10px;
  border-top-left-radius: 0;
  border-top-right-radius: 0;
}



</style>